package cn.itcast.service.impl;

import cn.itcast.dao.OrderSettingDao;
import cn.itcast.pojo.OrderSetting;
import cn.itcast.service.OrderSettingService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
    private OrderSettingDao orderSettingDao;

    @Override
    public List<Map> getOrderOrderSettingsByMonth(String date) {
        String s = date + "-1";
        String e = date + "-31";
        List<OrderSetting> list = orderSettingDao.getOrderOrderSettingsByMonth(s, e);
        List<Map> mapList = new ArrayList<>();
        for (OrderSetting orderSetting : list) {
            Map<String, Object> map = new HashMap<>();
            map.put("date", orderSetting.getOrderDate().getDate());
            map.put("number", orderSetting.getNumber());
            map.put("reservations", orderSetting.getReservations());
            mapList.add(map);
        }
        return mapList;
    }

    @Override
    public void importOrderSetting(ArrayList<OrderSetting> orderSettings) {
        for (OrderSetting orderSetting : orderSettings) {
            if (ObjectUtils.isEmpty(orderSettingDao.findOrderSettingByDate(orderSetting.getOrderDate()))) {
                orderSettingDao.insert(orderSetting);
            } else {
                orderSettingDao.updateOrderSettingNumber(orderSetting);
            }
        }
    }

    @Override
    public void updateOrderSettingNumber(OrderSetting orderSetting) {
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date date = simpleDateFormat.parse(simpleDateFormat.format(orderSetting.getOrderDate()));
            orderSetting.setOrderDate(date);
            if (ObjectUtils.isEmpty(orderSettingDao.findOrderSettingByDate(date))) {
                orderSettingDao.insert(orderSetting);
            } else {
                orderSettingDao.updateOrderSettingNumber(orderSetting);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}
